﻿using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace Cpjit.SunnyPaine.Toolkit.Net.Http.Impl
{
    public class HttpClientUtil : IHttpClient
    {
        private HttpClient client = null;

        public HttpClientUtil() : this(5)
        { }

        public HttpClientUtil(int timeout)
        {

        }

        public string Delete(string url, string strJson)
        {
            try
            {
                HttpContent content = null;
                Task<HttpResponseMessage> res = this.client.PostAsync(url, content);
                if (res.Result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    string str = res.Result.Content.ReadAsStringAsync().Result;
                    return str;
                }
                return null;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null && ex.InnerException.InnerException != null)
                {
                    throw new HttpRequestException(ex.InnerException.InnerException.Message, ex);
                }
                throw ex;
            }
        }

        public string Get(string url)
        {
            throw new NotImplementedException();
        }

        public string Post(string url, string strJson)
        {
            throw new NotImplementedException();
        }

        public string Put(string url, string strJson)
        {
            try
            {
                Task<HttpResponseMessage> res = client.GetAsync(url);
                if (res.Result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    string str = res.Result.Content.ReadAsStringAsync().Result;
                    return str;
                }
                return null;
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null && ex.InnerException.InnerException != null)
                {
                    throw new HttpRequestException(ex.InnerException.InnerException.Message, ex);
                }
                throw ex;
            }
        }
    }
}
